<template>
  <div class="uploader-wrap">
    <div class="uploader-tit">
      <div><span class="red-star" v-if="required">*</span>{{label}}<span v-if="isShowForcePhotoTxt" class="red-star">(强制拍照)</span></div>
      <div class="count-info">{{ value.length }}<span>/</span>{{ maxCount }}</div>
    </div>
    <div class="upload-box">
      <div class="uploaded-list" v-if="!readonly">
        <div class="file-item" v-for="(img, index) in value" :key="`img_${index}`">
          <img :src="img" @click="previewImg(index)" />
          <span class="delete" @click="deleteImg(index)">x</span>
        </div>
        <template v-if="isPhone">
          <div class="upload-btn" v-show="value.length < maxCount * 1" @click="changePhotograph">
            <van-icon name="plus" />
          </div>
        </template>
        <van-uploader v-else accept="*" class="upload-btn" :before-read="beforeRead" :after-read="afterRead"><van-icon name="plus" /></van-uploader>
      </div>
      <div class="uploaded-list" v-else>
        <div class="file-item" v-for="(img, index) in value" :key="`img_${index}`">
          <img :src="img" @click="previewImg(index)" />
        </div>
      </div>
    </div>
    <div class="tip" v-if="!readonly">仅限jpg,jpeg,png格式, 图片大小不超过{{ maxSize }}M</div>
  </div>
</template>

<script>
import { ImagePreview } from 'vant'
import { getPic, takePhoto } from '@/utils/nativeApi'
export default {
  name: 'uploadImg',
  props: {
    readonly: {
      // 该属性控制是否可以上传和删除文件，如果为false，则不显示上传和删除按钮
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: false
    },
    value: {
      // 文件列表
      type: [Array, String],
      default: () => []
    },
    maxCount: {
      type: [String, Number],
      default: 4
    },
    maxSize: {
      type: Number,
      default: 5
    },
    isOnlyCamera: {
      type: Boolean,
      default: false
    },
    label: {
      type: String,
      default: '上传图片'
    },
    isShowForcePhotoTxt: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    //  如果是手机
    isPhone() {
      let flag = false
      if (window.plus && window.plus.camera) {
        flag = true
      }
      return flag
    }
  },
  methods: {
    previewImg(index) {
      ImagePreview({
        images: [...this.value],
        startPosition: index
      })
    },
    deleteImg(index) {
      const temp = [...this.value]
      temp.splice(index, 1)
      const val = temp.length ? temp : ''
      this.$emit('input', val)
      this.$emit('change', val)
    },
    async changePhotograph() {
      let res = ''
      if (this.isOnlyCamera) {
        res = await takePhoto()
      } else {
        res = await getPic()
      }
      res = [res]
      if (this.maxCount) {
        if (res.length + this.value.length > this.maxCount) {
          this.$toast(`仅支持${this.maxCount}张以内图片！`)
          return false
        }
      }
      this.pictureTransForm(res)
    },
    TransForm(picArr, index = 0) {
      if (picArr.length) {
        let time = new Date()
        let key = time.getTime()
        this.$Posting(this.$api.getUploads, { imageStr: picArr[index], key: 'plan' + key + '.jpg' }).then((res) => {
          if (res.isSuccess) {
            // this.imgData.push(res.data)
            // this.$emit('uploadComplete', res.data) // 上传完成后触发uploadComplete事件
            this.$emit('input', [...this.value, res.data])
            this.$emit('change', [...this.value, res.data])
            if (index < picArr.length - 1) {
              index++
              this.TransForm(picArr, index)
            }
          }
        })
      }
    },
    pictureTransForm(picArr) {
      let arr = []
      for (let index = 0; index < picArr.length; index++) {
        arr.push(picArr[index])
      }
      this.TransForm(arr)
    },
    beforeRead(file) {
      console.log(file.type)
      if (/image/.test(file.type)) {
        return true
      } else {
        this.$toast('请选择图片格式的文件')
        return false
      }
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file)
      this.upload(file.file)
    },
    // 开始上传
    upload(fileObj) {
      // 不使用七牛上传部分
      let formData = new FormData()
      formData.append('file', fileObj)
      this.$Posting(this.$api.uploadFile, formData)
        .then((res) => {
          if (res.isSuccess) {
            console.log('上传成功：', res.data)
            const fileUrl = res.data.accessUrl
            this.$emit('input', [...this.value, fileUrl])
            this.$emit('change', [...this.value, fileUrl])
          } else {
            this.$emit('文件上传失败')
          }
        })
        .catch(() => {
          this.$emit('文件上传失败')
        })
    }
  }
}
</script>

<style lang="less" scoped>
/* 图片上传和附件的包裹样式 */
.uploader-wrap {
  background: #fff;
  .van-cell-group.van-hairline--top-bottom::after {
    display: none;
  }
  .uploader-tit {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    padding: 6px 0;
  }
  .tip {
    font-size: 12px;
    color: #969799;
    margin-bottom: 10px;
  }
}
.upload-box {
  .uploaded-list {
    display: flex;
    flex-wrap: wrap;
    .file-item {
      margin-right: 10px;
      margin-bottom: 10px;
      width: 70px;
      height: 70px;
      position: relative;
      img {
        display: block;
        width: 70px;
        height: 70px;
        border-radius: 4px;
      }
      .delete {
        position: absolute;
        top: -8px;
        right: -4px;
        width: 16px;
        height: 16px;
        background: red;
        border-radius: 50%;
        color: #fff;
        text-align: center;
        line-height: 16px;
        font-size: 12px;
      }
    }
    .upload-btn {
      width: 70px;
      height: 70px;
      margin-bottom: 10px;
      border: 1px solid #ccc;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      /deep/ .van-icon {
        font-size: 24px;
        color: #aaa;
      }
    }
  }
}
</style>
